/*
 * Created by Wildish on 2016-10-31
 *
 * Contact me with keithknight@qq.com
 *
 * Copyright (c) 2016 Wildish
 */

package com.wildish.hybridframework.utils.audio;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;

import com.wildish.hybridframework.core.HybridGlobal;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.Iterator;
import java.util.Map;

public class MediaPlayerHelper extends SoundBase {

    public MediaPlayerHelper(Context context) {
        super(context);
    }

    /**
     * 加载声音
     */
    public boolean loadSoundById(String key, SoundItem item) {
        if(!sMap.containsKey(key)) {
            item.setKey(key);
            sMap.put(key, item);
        }
        return true;
    }

    /**
     * 加载声音
     */
    public boolean loadSoundByPath(String key, SoundItem item) {
        if(!sMap.containsKey(key)) {
            File file = new File(item.getSoundPath());
            if(file.exists()) {
                item.setKey(key);
                sMap.put(key, item);
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 播放声音
     * @param key
     */
    public void playSound(final String key, String status) {
        final SoundItem item = sMap.get(key);
        if(item == null) {
            return;
        }
        try{
            switch (status) {
                case "play":
                    if(currentSound != null && !currentSound.getKey().equals(key) && currentSound.getStatus() == SoundItem.STATUS_PLAYING) {
                        if(currentSound.getPlayer() != null) {
                            currentSound.getPlayer().stop();
                        }
                        sMap.get(currentSound.getKey()).setStatus(SoundItem.STATUS_LOADED);
                    }

                    if(item.getPlayer() == null) {
                        boolean load = false;
                        if(StringUtils.isNotBlank(item.getSoundPath())) {
                            File file = new File(item.getSoundPath());
                            if(file.exists()) {
                                load = true;
                                MediaPlayer player = MediaPlayer.create(context, Uri.parse(item.getSoundPath()));
                                player.setLooping(false);
                                player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mp) {
                                        mp.release();
                                        sMap.get(key).setStatus(SoundItem.STATUS_LOADED);
                                        sMap.get(key).setPlayer(null);
                                    }
                                });
                                player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                    @Override
                                    public void onPrepared(MediaPlayer mp) {
                                        mp.start();
                                        sMap.get(key).setStatus(SoundItem.STATUS_PLAYING);
                                    }
                                });
                                item.setPlayer(player);
                            }
                        }
                        if(!load && item.getStreamId() != 0) {
                            MediaPlayer player = MediaPlayer.create(context, item.getRawId());
                            player.setLooping(false);
                            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                @Override
                                public void onCompletion(MediaPlayer mp) {
                                    mp.release();
                                    sMap.get(key).setStatus(SoundItem.STATUS_LOADED);
                                    sMap.get(key).setPlayer(null);
                                }
                            });
                            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                @Override
                                public void onPrepared(MediaPlayer mp) {
                                    mp.start();
                                    sMap.get(key).setStatus(SoundItem.STATUS_PLAYING);
                                }
                            });
                            item.setPlayer(player);
                        }
                    }
                    if(item.getPlayer() != null) {
                        if(item.getStatus() == SoundItem.STATUS_LOADED) {
                            item.getPlayer().prepare();
                        } else if(item.getStatus() == SoundItem.STATUS_PAUSE) {
                            item.getPlayer().start();
                        }
                    }
                    currentSound = item;
                    break;
                case "pause":
                    if(currentSound != null && currentSound.getKey().equals(key)) {
                        if(currentSound.getPlayer() != null && currentSound.getPlayer().isPlaying()) {
                            currentSound.getPlayer().pause();
                            sMap.get(currentSound.getKey()).setStatus(SoundItem.STATUS_PAUSE);
                        }
                    }
                    break;
            }
        } catch (Exception e) {
            HybridGlobal.logger.log(e);
        }
    }

    @Override
    public void releaseAll() {
        try{
            if(currentSound != null && currentSound.getPlayer() != null) {
                currentSound.getPlayer().stop();
            }
        }catch (Exception e) {
            HybridGlobal.logger.log(e);
        }

        for(Iterator<Map.Entry<String, SoundItem>> it = sMap.entrySet().iterator(); it.hasNext();) {
            SoundItem si = it.next().getValue();
            MediaPlayer player = si.getPlayer();
            if(player != null) {
                player.release();
            }
        }
        currentSound = null;
        sMap.clear();
    }
}
